package com.hontech.bv.ui.view

import android.content.Context
import android.util.AttributeSet
import android.view.LayoutInflater
import android.view.View
import android.widget.FrameLayout
import android.widget.TextView
import com.hontech.bv.R

class SwitchCtrlView(ctx: Context, attrs: AttributeSet) : FrameLayout(ctx, attrs) {

    private val mTvName: TextView
    private val mView: View

    private var mFlag = false

    init {
        val view = LayoutInflater.from(context).inflate(R.layout.view_switch_ctrl, this)
        mTvName = view.findViewById(R.id.id_view_sw_ctrl_name)
        mView = view.findViewById(R.id.id_view_sw_ctrl_sw)

        val attr = ctx.obtainStyledAttributes(attrs, R.styleable.SwitchCtrlView)
        val name = attr.getText(R.styleable.SwitchCtrlView_ctrl_name)
        mTvName.text = name
        attr.recycle()
        mView.setOnClickListener(::onClick)
    }

    var clickCb: (Boolean) -> Unit = {  }

    private fun onClick(_view: View) {
        mFlag = !mFlag
        update()
        clickCb(mFlag)
    }

    fun set(flag: Boolean) {
        mFlag = flag
        update()
    }

    fun isChecked() = mFlag

    private fun update() {
        if (mFlag) {
            mView.setBackgroundResource(R.drawable.ic_sw_on)
        } else {
            mView.setBackgroundResource(R.drawable.ic_sw_off)
        }
    }

}